// 引入第三方模块
const express = require('express');
// 引入连接池模块
const pool = require('../pool.js');
// 创建路由器对象
const r = express.Router();
// 轮播图图片增加
r.post('/add', (req, res, next) => {

    let obj = req.body;

    console.log(obj);

    // 判断不能为空
    if (!obj.sid) {
        res.send({
            code: 500,
            msg: 'sid不能为空'
        });
        return;
    }
    if (!obj.img) {
        res.send({
            code: 500,
            msg: 'img不能为空'
        });
        return;
    }
    if (!obj.title) {
        res.send({
            code: 500,
            msg: 'title不能为空'
        });
        return;
    }
    // sql增加数据
    pool.query('insert into swipe set ?', [obj], (err, result) => {
        if (err) {
            next(err);
            return;
        }
        if (result.length === 0) {
            res.send({
                code: 500,
                msg: '轮播图图片增加失败'
            });
        } else {
            
            res.send({
                code: 200,
                msg: '轮播图图片增加成功'
            });
        }
    })

});

// 轮播图图片删除
r.delete('/delete', (req, res, next) => {
    let obj = req.query.sid;
    console.log(obj);
    // 执行sql命令
    pool.query('delete from swipe where sid = ?', [obj], (err, result) => {
        if (err) {
            next(err);
            return;
        }
        console.log(result);
        if (result.affectedRows === 0) {
            res.send({
                code: 500,
                msg: '删除轮播图图片失败'
            });
        } else {
            res.send({
                code: 200,
                msg: '删除轮播图图片成功'
            });
        }
    })
});

// 轮播图图片修改
r.put('/put', (req, res, next) => {
    let obj = req.body;
    console.log(obj);
    // 执行sql命令
    pool.query('update swipe set ? where sid = ?', [obj, obj.sid], (err, result) => {
        if (err) {
            next(err)
            return;
        }
        console.log(result);
        if (result.affectedRows === 0) {
            res.send({
                code: 500,
                msg: '修改轮播图图片失败'
            });
        } else {
            res.send({
                code: 200,
                msg: '修改轮播图图片成功'
            });
        }
    });
});

// 轮播图图片查询
r.get('/search', (req, res, next) => {
    var obj = req.query.sid;
    console.log(obj);
    // 执行SQL命令
    pool.query("select * from swipe where sid = ?", [obj], (err, result) => {
        if (err) {
            next(err);
            return;
        }
        console.log(result);
        if (result.length === 0) {
            res.send({
                code: 500,
                msg: "查询失败"
            });
        } else {
            res.send({
                code: 200,
                msg: "查询成功",
                data: result
            });
        }
    })
})

// 导出路由器对象
module.exports = r;